﻿using AnlianCommon.API.Commands.Cottages;
using AnlianCommon.Common.Domains.SheepFarmHouse;
using AnlianCommon.Common.DTO;
using AnlianCommon.Common.Infrastructure.IRepository;
using AnlianCommon.Enum;
using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace AnlianCommon.API.Commands.Fields
{
    public class FieldSearchHander : IRequestHandler<FieldSearchCommand, Result<List<FieldCottageDto>>>
    {
        private readonly IMapper _mapper;
        private readonly IBaseRepository<Field>  _fieldRepository;
        private readonly IBaseRepository<Cottage> _cottageRepository;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="personnelRepository"></param>
        /// <param name="mapper"></param>
        public FieldSearchHander( IBaseRepository<Field> _fieldRepository,IBaseRepository<Cottage> _cottageRepository, IMapper mapper)
        {
            this._fieldRepository = _fieldRepository;
            this._cottageRepository = _cottageRepository;
            this._mapper = mapper;
        }

        /// <summary>
        /// 处理查看栏位命令
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result<List<FieldCottageDto>>> Handle(FieldSearchCommand request, CancellationToken cancellationToken)
        {
            var result = new Result<List<FieldCottageDto>> { Code = (int)CommonErrorCode.Search };
            try
            {
                var fields = await (from info in await _fieldRepository.GetAll()
                                    join cottage in await _cottageRepository.GetAll() on info.CottageId equals cottage.CottageId
                                    select new FieldCottageDto
                                    {
                                        CottageId = cottage.CottageId,
                                        FieldId = info.FieldId,
                                        CottageName = cottage.CottageName,
                                        FieldName = info.FieldName,
                                    }).Where(x => x.CottageId == request.CottageId).ToListAsync();
                result.Data = fields;
                return result;
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}
